<script setup>
import MyModal from '../../components/MyModal.vue';
import { onMounted, ref, defineAsyncComponent, nextTick } from 'vue';
import Button from '../../components/Button_lxw.vue';
import getRequest from '../../utils/lxw_request';
import Cookie from 'js-cookie';
import { useRouter } from 'vue-router';
import { setAvatar } from '../../utils/index.js';

const role_map = new Map();
role_map.set(1, "学生");
role_map.set(2, "老师");


const user_info = ref(null);
const avatar_img = ref(null)
const edit_introduction = ref("");

const isEdit = ref(false)
const textarea_ref = ref(null)

function editIntro() {
    isEdit.value = !(isEdit.value);
    if(isEdit.value == true) {
        nextTick(() => {

            textarea_ref.value.focus();
        })
    }
    
}

function getProfiles() {
    const cookie = Cookie.get('userData');
    const userData = cookie == undefined ? null : JSON.parse(cookie);

    getRequest(`/user/home_page/${userData['id']}`, "GET", new Headers({ 'Content-Type': 'application/json' }))
    .then((response) => response.json())
    .then((json) => {
        if (json.code === 200) {
            user_info.value = json.data;
            edit_introduction.value = user_info.value['introduction']
            getAvatar();
            setAvatar(user_info.value["avatar"]);
            
        } else {
            alert(json.msg);
        }
    })
    .catch((err) => {
        console.error(err);
    })

}

function getAvatar() {
    
    getRequest(`/static/avatar/${user_info.value["avatar"]}`, "GET")
    .then((response) => response.blob())
    .then((blob) => {
        const url = URL.createObjectURL(blob);
        avatar_img.value.src = url 
        avatar_img.value.onload = () => {
            URL.revokeObjectURL(url);
        }
    })
    .catch((err) => {
        console.error(err);
    })
}
const router = useRouter();
function updateAvatar() {
    if(this.img_file.value === null) {
        return ;
    }
    const form_data = new FormData();
    for (const file of this['img_file'].value) {
        form_data.append("avatar", file);
    }

    getRequest(`/user/avatar/update`, "POST", new Headers(), form_data)
    .then((response) => response.json())
    .then((json) => {
        if (json.code === 200) {
                alert("更换头像成功")
                getProfiles();
                setTimeout(() => {
                    history.go(0)
                }, 1500)
                closeModal();
            } else {
                alert(json.msg);
            }
    })
    .catch((err) => {
        console.error(err);
    })
}

function updateIntroduction() {
    if(edit_introduction.value === user_info.value['introduction']) {
        return ;
    }

    getRequest(`/user/account/update`, "POST", new Headers({ 'Content-Type': 'application/json' }), JSON.stringify({"introduction": edit_introduction.value}))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("修改个人简介成功")
                isEdit.value = false;
                getProfiles();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}
 
getProfiles();


// Modal
const isOpenModal = ref(false);
const modal_content_name = ref('');
const ModificationForm = defineAsyncComponent(() => import('../../components/ModificationForm.vue'));
const AvatarForm = defineAsyncComponent(() => import('../../components/AvatarForm.vue'));
const EmailForm = defineAsyncComponent(() => import('../../components/EmailForm.vue'));

function openModal(name) {
    modal_content_name.value = name;
    isOpenModal.value = true;
}

function closeModal() {
    modal_content_name.value = '';
    isOpenModal.value = false;
}

const info_key_map = [
    {key: 'name', label: '姓名', isEdit: false, isEnum: false},
    {key: 'nickName', label: '昵称', isEdit: true, isEnum: false},
    {key: 'role', label: '身份', isEdit: false, isEnum: true, enum: [{text: '学生', value: 1}, {text: '老师', value: 2}]},
    // {key: 'email', label: '邮箱', isEdit: false, isEnum: false},
    // {key: 'phone', label: '电话', isEdit: false, isEnum: false},
    {key: 'school', label: '学校', isEdit: false, isEnum: false},
    {key: 'college', label: '学院', isEdit: false, isEnum: false},
    {key: 'major', label: '专业', isEdit: false, isEnum: false},
    {key: 'grades', label: '班级', isEdit: false, isEnum: false}
]


function updateNickName() {
    if(user_info.value['nickName'] === this.edit_info.value['nickName']) {
        closeModal();
        return ;
    }
    getRequest(`/user/account/update`, "POST", new Headers({ 'Content-Type': 'application/json' }), JSON.stringify({nickName: this.edit_info.value['nickName']}))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("修改昵称成功")
                getProfiles();
                closeModal();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })

}

function updateEmail() {
    if(this.new_email.value === "" || this.code.value === "") {
        alert("邮箱和验证码不能为空");
        return ;
    }

    getRequest(`/user/account/email/update`, "POST", new Headers({ 'Content-Type': 'application/json' }), JSON.stringify({email: this.new_email.value, captcha: this.code.value}))
        .then((response) => response.json())
        .then((json) => {
            if (json.code === 200) {
                alert("更换邮箱成功");
                getProfiles();
                closeModal();
            } else {
                alert(json.msg);
            }
        })
        .catch((err) => {
            console.error(err);
        })
}

</script>
<template>
    <div class="profiles-container">
        <div class="profiles">
            <div class="personal-profile">
                <div class="avatar">
                    <img  ref="avatar_img" alt="Avatar" width="128">
                    <Button class="avatar-modification-button" @click="openModal('avatar')" >更换头像</Button>
                </div>
                <div class="info" v-if="user_info !== null">
                    <div class="head">
                        <div class="nick-name">
                            <p><span>昵称</span>{{ user_info['nickName']}}</p>
                        </div>
                        <div class="features">
                            <Button class="info-modification-button" @click="openModal('account')" >修改个人信息</Button>
                            <Button class="email-modification-button" @click="openModal('email')" >更换邮箱</Button>
                        </div>
                    </div>
                    <div class="content">
                        <div><span>姓名</span>{{ user_info['name']}}</div>
                        <div><span>身份</span>{{ role_map.get(user_info['role'])}}</div>
                        <div><span>邮箱</span>{{ user_info['email']}}</div>
                        <div><span>电话</span>{{ user_info['phone']}}</div>
                        <div><span>学校</span>{{ user_info['school']}}</div>
                        <div><span>学院</span>{{ user_info['college']}}</div>
                        <div><span>专业</span>{{ user_info['major']}}</div>
                        <div><span>班级</span>{{ user_info['grades']}}</div>
                    </div>

                </div>
                <div class="introduction" v-if="user_info !== null" >
                    <div class="head">
                        <div class="title">
                            <p>个人简介</p>
                        </div>
                        <div class="features">
                            <span @click="editIntro" >{{isEdit ? "取消" : "编辑"}}</span>
                            <span @click="updateIntroduction" >保存</span>
                        </div>
                    </div>
                    <div class="content" :class="{editing: isEdit}" >
                        {{ user_info['introduction'] }}
                    </div>
                    <textarea ref="textarea_ref" class="edit" :class="{editing: isEdit}" v-model="edit_introduction" ></textarea>
                </div>
            </div>
        </div>
        <MyModal  v-model:is-open-modal="isOpenModal" >
            <ModificationForm  v-if="modal_content_name === 'account'" :info="user_info" :map="info_key_map" :title="'修改个人信息'" :cancel-function="closeModal" :confirm-function="updateNickName" />
            <AvatarForm  v-if="modal_content_name === 'avatar'"  :cancel-function="closeModal" :confirm-function="updateAvatar" />
            <EmailForm  v-if="modal_content_name === 'email'"  :cancel-function="closeModal" :confirm-function="updateEmail" />
            
        </MyModal>
    </div>


</template>
<style scoped>
.profiles-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
}

.profiles-container>.profiles {
    /* display: flex;
    justify-content: center;
    flex-wrap: wrap;
    align-items: center; */
    background-color: #ffffff;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    width: 1057px;
    margin: 50px 0;
    padding: 15px 45px;
    border-radius: 10px;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
}

.profiles-container>.profiles>.personal-profile {
    display: grid;
    width: 100%;
    grid-template-areas: "avatar info"
        "introduction introduction";
    grid-template-columns: 20% 80%;
    font-family: Source Han Sans CN;
    font-size: 20px;
    color: #707070;
}

.profiles-container>.profiles>.personal-profile>.avatar {
    grid-area: avatar;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}


.profiles-container>.profiles>.personal-profile>.info {
    grid-area: info;
    display: flex;
    flex-direction: column;
}

.profiles-container>.profiles>.personal-profile>.info>.head {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 40px;
    margin-bottom: 60px;
}

.nick-name>p {
    font-family: Source Han Sans CN;
    font-weight: bold;
    font-size: 30px;
    line-height: 30px;
    color: #707070;
}

.nick-name span::after {
    content: ": ";
}

.profiles-container>.profiles>.personal-profile>.info>.head>.features {
    width: 340px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.info>.head>.features>button {
    margin: 0 10px;
    width: 162px;
    height: 40px;
    background-color: #8493a6;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    border-radius: 10px;
    font-family: Source Han Sans CN;
    font-size: 18px;
    line-height: 40px;
    color: #fafafa;
    border: none;
    user-select: none;
    cursor: pointer;
    padding: 0 0;
}

.info>.head>.features>button:hover {
    opacity: 0.85;
}

.info>.head>.features>button:active {
    transform: translateY(3px);
}

.avatar-modification-button,
.info-modification-button,
.email-modification-button {
    width: 162px !important;
    height: 40px !important;
    background-color: #8493a6 !important;
    border-color: transparent !important;
    font-size: 18px !important;
    line-height: 40px !important;
    color: #fafafa !important;
}

.avatar-modification-button {
    width: 120px !important;
    margin: 0 auto;
    margin-top: 10%;
}

.profiles-container>.profiles>.personal-profile>.info>.content {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}

.profiles-container>.profiles>.personal-profile>.info>.content>div {
    width: 50%;
    margin-bottom: 20px;
}

.profiles-container>.profiles>.personal-profile>.info>.content>div>span::after {
    content: ': '
}


.profiles-container>.profiles>.personal-profile>.introduction {
    grid-area: introduction;

}

.profiles-container>.profiles>.personal-profile>.introduction>.head {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.profiles-container>.profiles>.personal-profile>.introduction>.head>.title>p {
    font-family: Source Han Sans CN;
    font-size: 24px;
    font-weight: bold;
    line-height: 24px;
    color: #707070;
}

.profiles-container>.profiles>.personal-profile>.introduction>.head>.features>span {
    display: inline-block;
    font-family: Source Han Sans CN;
    font-size: 16px;
    font-weight: normal;
    line-height: 16px;
    color: #8493a6;
    margin-right: 20px;
    cursor: pointer;

}

.profiles-container>.profiles>.personal-profile>.introduction>.head>.features>span:hover {
    opacity: 0.85;
}

.profiles-container>.profiles>.personal-profile>.introduction>.content {
    border: solid 1px #707070;
    padding: 10px 20px;
    height: 158px;
    overflow: auto;
}

.profiles-container>.profiles>.personal-profile>.introduction>.content.editing {
    display: none;
}

.profiles-container>.profiles>.personal-profile>.introduction>.edit {
    display: none;
    width: 100%;
    height: 158px;
    overflow: auto;
    padding: 10px 20px;
    font-family: Source Han Sans CN;
    font-size: 20px;
    color: #606266;
}

.profiles-container>.profiles>.personal-profile>.introduction>.edit.editing {
    display: block;
    background-color: #F2F3F5;
}

</style>